package com.jolink.omiis.wechat.message;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jolink.omiis.wechat.BusinessEntry;
import com.jolink.omiis.wechat.SpringContextUtil;
import com.jolink.omiis.wechat.api.CSMessageBuilder;
import com.jolink.omiis.wechat.api.ICustomerService;
import com.jolink.omiis.wechat.api.IMaterialApi;
import com.jolink.omiis.wechat.api.IRobotApi;
import com.jolink.omiis.wechat.api.IUserOperationApi;
import com.jolink.omiis.wechat.api.IWeChatBrokerMessage;
import com.jolink.omiis.wechat.faq.ExpressionConfiguration;
import com.jolink.omiis.wechat.inner.ConversationType;
import com.jolink.omiis.wechat.inner.IOmiisMessager;
import com.jolink.omiis.wechat.keys.IPreferences;
import com.jolink.omiis.wechat.message.bean.request.MessageRequestBase;
import com.jolink.omiis.wechat.message.bean.request.ImageMessageRequest;
import com.jolink.omiis.wechat.message.bean.request.SubscribeEventRequest;
import com.jolink.omiis.wechat.message.bean.request.TextMessageRequest;
import com.jolink.omiis.wechat.message.bean.request.UnsubscribeEventRequest;
import com.jolink.omiis.wechat.message.bean.request.VideoMessageRequest;
import com.jolink.omiis.wechat.message.bean.request.VoiceMessageRequest;
import com.jolink.omiis.wechat.message.type.EventType;
import com.jolink.omiis.wechat.message.type.MessageType;
import com.jolink.omiis.wechat.outer.WeChatResponse;
import com.jolink.omiis.wechat.redis.IRedisProcessor;
import com.jolink.omiis.wechat.util.DateUtil;
import com.jolink.omiis.wechat.util.GsonUtil;
import com.jolink.omiis.wechat.util.SFTPUtil;
import com.jolink.omiis.wechat.util.CacheUtil;
import com.jolink.omiis.wechat.util.WeChatConfiguration;
import com.jolink.omiis.wechat.util.XmlParser;
import com.jolink.omiis.wechat.util.XmlUtil;

/**
 * 处理中继微信用户信息 方便客户接入全媒体客服 公众号后台负责消息的转发 消息流程：
 * 微信用户->腾讯服务器->公众号后台->全媒体-微信后台->全媒体Bus-> 减少客户开发工作量
 * 
 * @author WangYanqing
 *
 */
@Deprecated
public class BrokerMessageHandler extends AbstractMessageHandler implements IMessageHandler {
	public BrokerMessageHandler() {
	}

	private static final Logger logger = LoggerFactory.getLogger(BrokerMessageHandler.class);

	@Override
	public WeChatResponse handleMessage() throws Exception {
		long t1 = System.currentTimeMillis();
		String reqestMessage = getReqMessage();
		Document doc = XmlParser.str2Xml(reqestMessage);
		Element msgTypeElement = (Element) doc.selectSingleNode("/xml/MsgType");
		Element fromUserNameElement = (Element) doc.selectSingleNode("/xml/FromUserName");
		logger.info("开始处理微信用户：{}请求，内容：{}。", fromUserNameElement, reqestMessage);
		String fromUserName = fromUserNameElement.getTextTrim();
		MessageType mt = MessageType.valueOf(msgTypeElement.getTextTrim().toUpperCase());
		logger.info("微信用户：{}，msgTypeElement：{}，消息类型：{}。", fromUserName, msgTypeElement.getTextTrim(), mt);
		switch (mt) {
		case TEXT:
			processTextRequest();
			break;
		case VIDEO:
			processVideoRequest();
			break;
		case SHORTVIDEO:
			processShortVideoRequest();
			break;
		case IMAGE:
			processImageRequest();
			break;
		case LOCATION:
			processLocationRequest();
			break;
		case LINK:
			processLinkRequest();
			break;
		case EVENT:
			Element eventTypeE = (Element) doc.selectSingleNode("/xml/Event");
			String eventTypeStr = eventTypeE.getTextTrim();
			EventType et = EventType.valueOf(eventTypeStr.toUpperCase());
			logger.info("微信用户：{}，EventType：{}", fromUserName, eventTypeStr);
			switch (et) {
			case SUBSCRIBE:
				processSubscribeRequest();
				break;
			case UNSUBSCRIBE:
				processUnsubscribeRequest();
				break;
			default:
				// ?
				break;
			}
			break;
		case VOICE:
			processVoiceRequest();
			break;
		default:
			break;
		}
		// TODO WeChatResponse 可能会废弃，微信用户信息采用异步处理，后续做修正 20160908 by wangyq
		WeChatResponse wr = createDefaultWeChatResponse();
		long t2 = System.currentTimeMillis();
		logger.info("处理微信用户请求：{}完成，耗时：{}毫秒。", fromUserName, (t2 - t1));
		return wr;
	}

	private static boolean checkInSession(Map<String, String> userBaseInfo) {
		String sessionIdKey = "session_id";
		if (!userBaseInfo.containsKey(sessionIdKey)) {
			return false;
		}
		String sessionId = userBaseInfo.get(sessionIdKey);
		if (StringUtils.isEmpty(sessionId)) {
			return false;
		}
		return true;
	}

	/**
	 * 处理视频信息
	 */
	private void processVideoRequest() {
		long t1 = System.currentTimeMillis();
		VideoMessageRequest request = (VideoMessageRequest) transfer2Obj(getReqMessage(), VideoMessageRequest.class);
		String open_id = request.getFromUserName();
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(open_id)));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (checkInSession(userBaseInfo)) {
			String sessionId = userBaseInfo.get("session_id");
			Map<String, String> userSessionInfo = new HashMap<String, String>();
			try {
				userSessionInfo.putAll(redis.hgetall(CacheUtil.getSessionKey(sessionId)));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
			userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
			try {
				redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			String mediaId = request.getMediaId();
			String downloadPath = WeChatConfiguration.getIngleton().getValue("TENCENT_MATERIAL_DOWN_PATH");
			IMaterialApi materialApi = SpringContextUtil.getBean(IMaterialApi.class);
			String app_id = userSessionInfo.get("app_id");
			Map<String, String> mediaInfo = materialApi.downloadTempMaterial(app_id, mediaId);
			logger.info("下载素材结果：{}", mediaInfo);
			String fileName = mediaInfo.get("fileName");
			String tempPath = mediaInfo.get("tempPath");
			logger.info("腾讯素材下载路径：{}，mediaId：{}，fileName：{}", downloadPath, mediaId, fileName);
			SFTPUtil.put(tempPath + File.separator + fileName,
					WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_PATH"));
			String fileUrl = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_BASE_URL") + fileName;
			logger.info("MediaURL：{}。", fileUrl);
			// Map<String, String> msg = new HashMap<String, String>();
			// msg.putAll(userSessionInfo);
			// msg.put("msgContent", fileUrl);
			// msg.put("senderId", userSessionInfo.get("senderId"));
			// msg.put("receiverId", userSessionInfo.get("receiverId"));
			// msg.put("conversationId", userSessionInfo.get("conversationId"));
			// msg.put("msgType", request.getMsgType().toUpperCase());
			Map<String, String> msg = createOmiisMessage(userSessionInfo, MessageType.VIDEO.toString(), fileUrl);
			getMessager().sendMessage(msg);
			// SessionManager.getSesssionManager().updateSession(open_id,
			// msg.get("previous_message_timestamp"));
		} else {
			// TODO 待修改
			String senderId = userBaseInfo.get("open_id");
			IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
			broker.response(CSMessageBuilder.createMessage(senderId, MessageType.TEXT.getValue(),
					ExpressionConfiguration.createDefaultFAQ()));
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理微信用户：{}，视频请求耗时：{}毫秒。", request.getFromUserName(), (t2 - t1));
	}

	/**
	 * 处理小视频信息
	 */
	private void processShortVideoRequest() {
		processVideoRequest();
	}

	/**
	 * 处理音频信息
	 */
	private void processVoiceRequest() {
		VoiceMessageRequest request = (VoiceMessageRequest) transfer2Obj(getReqMessage(), VoiceMessageRequest.class);
		long t1 = System.currentTimeMillis();
		String open_id = request.getFromUserName();
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(open_id)));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (checkInSession(userBaseInfo)) {
			String session_id = userBaseInfo.get("session_id");
			Map<String, String> userSessionInfo = new HashMap<String, String>();
			try {
				userSessionInfo.putAll(redis.hgetall(CacheUtil.getSessionKey(session_id)));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
			userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
			try {
				redis.hmset(CacheUtil.getSessionKey(session_id), userSessionInfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			String mediaId = request.getMediaId();
			String downloadPath = WeChatConfiguration.getIngleton().getValue("TENCENT_MATERIAL_DOWN_PATH");
			IMaterialApi materialApi = SpringContextUtil.getBean(IMaterialApi.class);
			String app_id = userSessionInfo.get("app_id");
			Map<String, String> mediaInfo = materialApi.downloadTempMaterial(app_id, mediaId);
			logger.info("下载素材结果：{}", mediaInfo);
			String fileName = mediaInfo.get("fileName");
			String tempPath = mediaInfo.get("tempPath");
			logger.info("腾讯素材下载路径：{}，mediaId：{}，fileName：{}", downloadPath, mediaId, fileName);
			SFTPUtil.put(tempPath + File.separator + fileName,
					WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_PATH"));
			String fileUrl = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_BASE_URL") + fileName;
			logger.info("Media URL：{}", fileUrl);
			// 音频文件需要传送音频时长，用^分隔符
			// Map<String, String> msg = new HashMap<String, String>();
			// msg.putAll(userSessionInfo);
			// msg.put("msgContent", fileUrl + "^" + mediaInfo.get("duration"));
			// // msg.put("senderId", userSessionInfo.get("receiverId"));
			// // msg.put("receiverId", userSessionInfo.get("senderId"));
			// msg.put("senderId", userSessionInfo.get("senderId"));
			// msg.put("receiverId", userSessionInfo.get("receiverId"));
			// msg.put("conversationId", userSessionInfo.get("conversationId"));
			// msg.put("msgType", "AUDIO");
			Map<String, String> msg = createOmiisMessage(userSessionInfo, "AUDIO",
					fileUrl + "^" + mediaInfo.get("duration"));
			getMessager().sendMessage(msg);
			// SessionManager.getSesssionManager().updateSession(open_id,
			// msg.get("previous_message_timestamp"));
		} else {
			// TODO
			// String senderId = userBaseInfo.get("open_id");
			// IWeChatBrokerMessage broker =
			// SpringContextUtil.getBean(IWeChatBrokerMessage.class);
			// broker.response(
			// CSMessageBuilder.createMessage(open_id,
			// MessageType.TEXT.getValue(),
			// ExpressionConfiguration.createDefaultFAQ()));
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理微信用户：{}，视频请求耗时：{}毫秒。", request.getFromUserName(), (t2 - t1));
	}

	/**
	 * 处理图片信息
	 */
	private void processImageRequest() {
		ImageMessageRequest request = (ImageMessageRequest) transfer2Obj(getReqMessage(), ImageMessageRequest.class);
		long t1 = System.currentTimeMillis();
		String open_id = request.getFromUserName();
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(open_id)));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (checkInSession(userBaseInfo)) {
			String session_id = userBaseInfo.get("session_id");
			Map<String, String> userSessionInfo = new HashMap<String, String>();

			try {
				userSessionInfo.putAll(redis.hgetall(CacheUtil.getSessionKey(session_id)));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
			userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
			try {
				redis.hmset(CacheUtil.getSessionKey(session_id), userSessionInfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			String mediaId = request.getMediaId();

			IMaterialApi materialApi = SpringContextUtil.getBean(IMaterialApi.class);
			String app_id = userSessionInfo.get("app_id");
			Map<String, String> mediaInfo = materialApi.downloadTempMaterial(app_id, mediaId);
			logger.info("下载素材结果：{}", mediaInfo);
			String fileName = mediaInfo.get("fileName");
			String tempPath = mediaInfo.get("tempPath");
			logger.info("腾讯素材下载路径：{}，mediaId：{}，fileName：{}", tempPath, mediaId, fileName);
			SFTPUtil.put(tempPath + File.separator + fileName,
					WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_UPLOAD_PATH"));
			String fileUrl = WeChatConfiguration.getIngleton().getValue("OMIIS_MATERIAL_BASE_URL") + fileName;
			logger.info("Media URL：{}", fileUrl);
			// Map<String, String> msg = new HashMap<String, String>();
			// msg.putAll(userSessionInfo);
			// msg.put("msgContent", fileUrl);
			// msg.put("senderId", userSessionInfo.get("senderId"));
			// msg.put("receiverId", userSessionInfo.get("receiverId"));
			// msg.put("conversationId", userSessionInfo.get("conversationId"));
			// msg.put("msgType", request.getMsgType().toUpperCase());
			Map<String, String> msg = createOmiisMessage(userSessionInfo, MessageType.IMAGE.toString(), fileUrl);
			getMessager().sendMessage(msg);
			// SessionManager.getSesssionManager().updateSession(open_id,
			// msg.get("previous_message_timestamp"));
		} else {
			// TODO
			// String senderId = userBaseInfo.get("open_id");
			// IWeChatBrokerMessage broker =
			// SpringContextUtil.getBean(IWeChatBrokerMessage.class);
			// broker.response(
			// CSMessageBuilder.createMessage(senderId,
			// MessageType.TEXT.getValue(),
			// ExpressionConfiguration.createDefaultFAQ()));
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理客户：{}，视频请求耗时：{}毫秒。", request.getFromUserName(), (t2 - t1));
	}

	/**
	 * 处理链接信息
	 */
	private void processLinkRequest() {

	}

	/**
	 * 处理分享位置信息
	 */
	private void processLocationRequest() {

	}

	/**
	 * 处理微信用户关注
	 */
	private void processSubscribeRequest() {
		long t1 = System.currentTimeMillis();
		logger.info("开始处理微信客户订阅请求：");
		SubscribeEventRequest request = (SubscribeEventRequest) transfer2Obj(getReqMessage(),
				SubscribeEventRequest.class);

		String fromUserName = request.getFromUserName();
		// TODO 添加欢迎语、结果发送至中继服务器
		String message = CSMessageBuilder.createMessage(fromUserName, MessageType.TEXT.getValue(),
				getContext().getServiceUtil().getExpression().getWelcome());
		IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(fromUserName)));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		broker.response(message);
		long t2 = System.currentTimeMillis();
		logger.info("处理微信客户：{}，订阅请求耗时：{}毫秒。", fromUserName, (t2 - t1));
	}

	/**
	 * 微信用户取消关注公众号 1、在库中记录做相应标记为取消关注
	 */
	private void processUnsubscribeRequest() {
		long t1 = System.currentTimeMillis();
		logger.info("开始处理微信用户取消订阅请求：");
		UnsubscribeEventRequest request = (UnsubscribeEventRequest) transfer2Obj(getReqMessage(),
				UnsubscribeEventRequest.class);
		String fromUserName = request.getFromUserName();
		long t2 = System.currentTimeMillis();
		logger.info("处理微信用户：{}，取消订阅请求耗时：{}毫秒。", fromUserName, (t2 - t1));
	}

	/**
	 * 处理文本请求
	 */
	private void processTextRequest() {
		long t1 = System.currentTimeMillis();
		TextMessageRequest request = (TextMessageRequest) transfer2Obj(getReqMessage(), TextMessageRequest.class);
		ICustomerService cs = SpringContextUtil.getBean(ICustomerService.class);
		IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
		String fromUserName = request.getFromUserName();
		logger.info("开始处理微信用户：{}请求，内容：{}。", fromUserName, request.getContent());
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(fromUserName)));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		if (checkInSession(userBaseInfo)) {
			String sessionId = userBaseInfo.get("session_id");
			Map<String, String> userSessionInfo = new HashMap<String, String>();
			try {
				userSessionInfo.putAll(redis.hgetall(CacheUtil.getSessionKey(sessionId)));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			String conversation_type = userSessionInfo.get("conversation_type");
			ConversationType ct = ConversationType.valueOf(conversation_type.toUpperCase());
			if (ConversationType.ROBOT == ct || ConversationType.CONFIRM_BUSINESS_TYPE == ct) {
				logger.info("微信用户：{}，由智能机器人服务。", fromUserName);
				processRobot();
				return;
			}
			logger.info("微信用户：{}，在人工坐席会话中。", fromUserName);
			Map<String, String> msg = new HashMap<String, String>();
			switch (ct) {
			case RESOURCE_REQUEST:
			case EVENT_WAITING:
				TextMessageRequest tmr = request;
				String message = tmr.getContent();
				String content = null;
				if ("2".equals(message)) {
					content = "尊敬的顾客：很抱歉，人工客服繁忙，您可通过拨打服务电话进行咨询。\n服务热线：010-69543910";
					// msg.put("senderId", userSessionInfo.get("senderId"));
					// msg.put("receiverId", userSessionInfo.get("receiverId"));
					// msg.put("conversationId",
					// userSessionInfo.get("conversationId"));
					// msg.put("msgType", ConversationType.HANGUP.toString());
					// IOmiisMessager messager =
					// SpringContextUtil.getBean(IOmiisMessager.class);
					// messager.sendMessage(msg);
					// msg = createOmiisMessage(userSessionInfo,
					// ConversationType.HANGUP.toString(), "");
					getMessager()
							.sendMessage(createOmiisMessage(userSessionInfo, ConversationType.HANGUP.toString(), ""));
					try {
						String result = redis.hdel(CacheUtil.getUserKey(userBaseInfo.get("openid")), "session_id");
						logger.info("微信用户：{}，注销会话：{}，操作结果:{}", request.getFromUserName(), ConversationType.HANGUP,
								result);
						userSessionInfo.put("conversation_type", ConversationType.HANGUP.toString());
						// 20161213 update by wangyq
						redis.hmset(CacheUtil.getSessionKey(userBaseInfo.get("session_id")), userSessionInfo);
						// SessionManager.getSesssionManager().removeSession(userBaseInfo.get("openid"));
						logger.info("微信用户：{}主动结束本次对话。", fromUserName);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				} else if ("1".equals(message)) {
					content = "转接中，请稍候。您可以先简单描述一下您的问题，以便服务人员尽快为您解答......";
				}
				// TODO
				String appId = userBaseInfo.get("app_id");
				String rspMsg = CSMessageBuilder.createMessage(userSessionInfo.get("open_id"),
						MessageType.TEXT.getValue(), content);

				if (StringUtils.isEmpty(appId)) {
					broker.response(rspMsg);
				} else {
					cs.send(appId, rspMsg);
				}
				break;
			case EVENT_TALK:
				logger.info("微信用户：：{}在会话当中，会话信息：{}。", request.getFromUserName(), userSessionInfo);
				// msg.put("msgContent", request.getContent());
				// msg.put("senderId", userSessionInfo.get("senderId"));
				// msg.put("receiverId", userSessionInfo.get("receiverId"));
				// msg.put("conversationId",
				// userSessionInfo.get("conversationId"));
				// msg.put("msgType", MessageType.TEXT.toString());
				logger.info("微信用户：{}在会话当中，将信息转发至客服。", fromUserName);
				getMessager().sendMessage(
						createOmiisMessage(userSessionInfo, MessageType.TEXT.toString(), request.getContent()));
				// getMessager().sendMessage(msg);
				break;
			case SATISFACTION_SURVEY:
				logger.info("更新满意度。");
			case NO_REPLAY_NOTIFICATION:
				content = request.getContent().trim();
				logger.info("微信用户：{}针对指定时间未回复通知回复内容：{}。", request.getFromUserName(), content);
				if ("1".equals(content)) {
					msg.put("senderId", userSessionInfo.get("senderId"));
					msg.put("receiverId", userSessionInfo.get("receiverId"));
					msg.put("conversationId", userSessionInfo.get("conversationId"));
					msg.put("msgType", ConversationType.HANGUP.toString());
					// getMessager().sendMessage(msg);
					getMessager()
							.sendMessage(createOmiisMessage(userSessionInfo, ConversationType.HANGUP.toString(), ""));
					userSessionInfo.put("conversation_type", ConversationType.HANGUP.getValue());
					logger.info("微信用户：{}，会话信息：{}，回复内容：{}自动退出。", request.getFromUserName(), userSessionInfo,
							request.getContent());
					// SessionManager.getSesssionManager().removeSession(request.getFromUserName());
					content = "本次会话结束。";
					try {
						String result = redis.hdel(CacheUtil.getUserKey(fromUserName), "session_id");
						// TODO
						appId = userBaseInfo.get("app_id");
						rspMsg = CSMessageBuilder.createMessage(userSessionInfo.get("open_id"),
								MessageType.TEXT.getValue(), content);
						if (StringUtils.isEmpty(appId)) {
							broker.response(rspMsg);
						} else {
							cs.send(appId, rspMsg);
						}
						// cs =
						// SpringContextUtil.getBean(ICustomerService.class);
						logger.info("微信用户：{}，结束会话，注销该用户排队信息，操作结果：{}", fromUserName, result);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
					logger.info("微信用户：{}自动结束本次对话。", fromUserName);
				} else {
					// msg.put("senderId", userSessionInfo.get("senderId"));
					// msg.put("receiverId", userSessionInfo.get("receiverId"));
					// msg.put("conversationId",
					// userSessionInfo.get("conversationId"));
					// msg.put("userRole", "CUSTOMER");
					// msg.put("msgType", MessageType.TEXT.toString());
					// msg.put("msgContent", content);
					userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
					userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
					userSessionInfo.put("conversation_type", ConversationType.EVENT_TALK.getValue());
					// getMessager().sendMessage(msg);
					getMessager()
							.sendMessage(createOmiisMessage(userSessionInfo, MessageType.TEXT.toString(), content));
					logger.info("微信用户：{}，会话状态由：{}转为：{}", fromUserName, ConversationType.HANGUP.getValue(),
							ConversationType.EVENT_TALK.getValue());
					try {
						redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
						// SessionManager.getSesssionManager().updateSession(fromUserName,
						// userSessionInfo.get("previous_message_timestamp"));
						logger.info("微信用户：{}，更新排队信息：{}。", fromUserName, userSessionInfo);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}
			default:
				break;
			}
		} else {
			logger.info("微信用户：{}，接入智能机器人。");
			processRobot();
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理微信用户：{}，请求耗时：{}毫秒。", fromUserName, (t2 - t1));
	}

	/**
	 * 微信用户选择人工，提示微信用户选择业务类型，选择对应技能组
	 * 
	 * @param userSessionInfo
	 */
	private void sendBusinessType(Map<String, String> userSessionInfo) {
		List<BusinessEntry> businesses = getContext().getBusinesses();
		StringBuffer businessTypeStr = new StringBuffer();
		businessTypeStr.append("回复如下序号，以便为您提供更精准的服务。").append("\n");
		for (int i = 0; i < businesses.size(); i++) {
			BusinessEntry entry = businesses.get(i);
			businessTypeStr.append(entry.getId()).append("、").append(entry.getName());
			if (i < businesses.size() - 1) {
				businessTypeStr.append("\n");
			}
		}
		logger.info("待微信用户选择的业务类型：{}。", businessTypeStr.toString());
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		String senderId = userSessionInfo.get("open_id");
		String sessionId = userSessionInfo.get("session_id");
		// logger.info("微信用户：{}，申请人工坐席，SessionId：{}。", senderId, sessionId);
		// Map<String, String> message = new HashMap<String, String>();
		// message = new HashMap<String, String>();
		// message.put("senderId", userSessionInfo.get("sender_id"));
		// message.put("senderName", userSessionInfo.get("sender_name"));
		// message.put("conversationId", userSessionInfo.get("conversationId"));
		// message.put("msgType",
		// ConversationType.CONFIRM_BUSINESS_TYPE.toString());
		logger.info("发送待确认业务类型至微信用户：{}，会话ID：{}，内容：{}，会话信息：{}。", senderId, sessionId, businessTypeStr.toString(),
				userSessionInfo);
		// IOmiisMessager messager =
		// SpringContextUtil.getBean(IOmiisMessager.class);
		// messager.sendMessage(message);
		userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
		userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
		userSessionInfo.put("conversation_type", ConversationType.CONFIRM_BUSINESS_TYPE.getValue());
		// SessionManager.getSesssionManager().updateSession(senderId,
		// userSessionInfo.get("previous_message_timestamp"));
		try {
			String appId = userSessionInfo.get("app_id");
			redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
			// TODO
			String message = CSMessageBuilder.createMessage(senderId, MessageType.TEXT.getValue(),
					businessTypeStr.toString());
			if (StringUtils.isEmpty(appId)) {
				IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
				broker.response(message);
			} else {
				ICustomerService cs = SpringContextUtil.getBean(ICustomerService.class);
				cs.send(appId, message);
			}
			logger.info("发送待确认业务类型至微信用户：{}，同时更新会话信息：{}。", senderId, userSessionInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	@SuppressWarnings("rawtypes")
	private void processRobot() {
		long t1 = System.currentTimeMillis();
		TextMessageRequest request = (TextMessageRequest) transfer2Obj(getReqMessage(), TextMessageRequest.class);
		logger.info("智能机器人开始处理微信用户：{}，请求：", request.getFromUserName());
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(request.getFromUserName())));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		String sessionId = userBaseInfo.get("session_id");
		Map<String, String> userSessionInfo = new HashMap<String, String>();
		// step-1 客户入队
		if (StringUtils.isEmpty(sessionId)) {
			userSessionInfo.putAll(enqueue(request.getToUserName(), request.getFromUserName()));
		} else {
			try {
				userSessionInfo.putAll(redis.hgetall(CacheUtil.getSessionKey(sessionId)));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		sessionId = userSessionInfo.get("session_id");
		String conversationType = userSessionInfo.get("conversation_type");
		String previousAnswerTypeId = userSessionInfo.get("answerTypeId");
		logger.info("微信用户：{}，会话ID：{}，conversationType：{}，机器人上次回复结果：{}。", request.getFromUserName(), sessionId,
				conversationType, previousAnswerTypeId);
		if (ConversationType.CONFIRM_BUSINESS_TYPE == ConversationType.valueOf(conversationType.toUpperCase())) {
			if (getContext().getBusinessIdAndName().containsKey(request.getContent())) {
				userSessionInfo.put("businessType", getContext().getBusinessIdAndName().get(request.getContent()));
			} else {
				// TODO 针对客户输入其他选项，未必和其他队列码对应，统一重置为默认的其他业务队列
				String defaultBusinessTypeId = "5";
				userSessionInfo.put("businessType", defaultBusinessTypeId);
			}
			logger.info("发送申请人工坐席请求。");
			String content = "正在为您转接人工，请稍候......";
			// TODO
			ICustomerService cs = SpringContextUtil.getBean(ICustomerService.class);
			IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
			String appId = userBaseInfo.get("app_id");
			String rspMsg = CSMessageBuilder.createMessage(request.getFromUserName(), MessageType.TEXT.getValue(),
					content);
			if (StringUtils.isEmpty(appId)) {
				broker.response(rspMsg);
			} else {
				cs.send(userBaseInfo.get("app_id"), rspMsg);
			}
			sendResourceRequest(userSessionInfo);
			return;
		}
		if ("1".equals(previousAnswerTypeId) || "3".equals(previousAnswerTypeId) || "7".equals(previousAnswerTypeId)) {
			if ("9".equals(request.getContent())) {
				String senderId = userSessionInfo.get("open_id");
				logger.info("开始为微信用户：{}申请坐席资源，会话ID：{}，发送业务类型至微信用户，确定咨询业务主题。", senderId, sessionId);
				// sendResourceRequest(userSessionInfo);
				// userSessionInfo.put("previous_message_time",
				// DateUtil.getCurrentDate());
				// userSessionInfo.put("previous_message_timestamp",
				// DateUtil.getCurrentTimeMillis());
				// userSessionInfo.put("conversation_type",
				// ConversationType.RESOURCE_REQUEST.getValue());
				// sendResourceRequest(userSessionInfo);
				sendBusinessType(userSessionInfo);
				userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
				userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
				userSessionInfo.put("conversation_type", ConversationType.CONFIRM_BUSINESS_TYPE.getValue());
				try {
					redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
				// SessionManager.getSesssionManager().updateSession(request.getFromUserName(),
				// userSessionInfo.get("previous_message_timestamp"));
				return;
			}
		}
		// step-2 访问机器人
		// 再获取一次微信用户信息
		try {
			userBaseInfo.putAll(redis.hgetall(CacheUtil.getUserKey(request.getFromUserName())));
		} catch (Exception e1) {
			logger.error(e1.getMessage(), e1);
		}
		IRobotApi robot = SpringContextUtil.getBean(IRobotApi.class);
		String conversationId = userSessionInfo.get("conversationId");
		// String conversationId = userSessionInfo.get("conversationId") == null
		// ? ""
		// : userSessionInfo.get("conversationId");
		// 20161024 update by wangyq 访问机器人获取conversationId，用于调用机器人接口凭证
		String openId = userBaseInfo.get("openid");
		if (StringUtils.isEmpty(conversationId)) {
			String conversationIdResult = (String) robot.getConversationId(openId, IPreferences.WECHAT_DEFAULT_WELCOME,
					IPreferences.CHANNEL_ID);
			logger.info("会话ID不存在，调用机器人接口获取会话ID，结果：{}。", conversationIdResult);
			JsonObject conversationJson = GsonUtil.json2JsonObject(conversationIdResult);
			String code = conversationJson.get("code").getAsString();
			logger.info("code：{}。", code);
			if ("0".equals(code)) {
				conversationId = conversationJson.getAsJsonObject("map").get("conversationId").getAsString();
				logger.info("申请会话ID成功，conversationId：{}。", conversationId);
			} else {
				// TODO 申请ID失败，如何做后续操作？
				logger.error("获取会话ID失败！");
			}
			// 这个操作可以去掉，后面还有更新动作
			// userSessionInfo.put("conversationId", conversationId);
			// try {
			// redis.hmset(SessionUtil.getSessionKey(sessionId),
			// userSessionInfo);
			// } catch (Exception e) {
			// logger.error(e.getMessage(), e);
			// }
		}
		IWeChatBrokerMessage broker = SpringContextUtil.getBean(IWeChatBrokerMessage.class);
		String result = (String) robot.query2(request.getFromUserName(), request.getContent(), conversationId,
				IPreferences.CHANNEL_ID);
		JsonObject answertObject = GsonUtil.json2JsonObject(result);
		String rspCode = answertObject.get("code").getAsString();
		String answerTypeId = "6";
		String answerMessage = "";
		StringBuffer messageBuffer = new StringBuffer();
		if (!"0".equals(rspCode)) {
			answerTypeId = "1";
			answerMessage = CSMessageBuilder.createMessage(openId, MessageType.TEXT.getValue(),
					messageBuffer.append("机器人无法理解您的意思，如需人工，请回复序号9。").toString());
			logger.error("智能机器人返回信息异常，回复微信用户信息：{}", answerMessage);
		} else {
			String detailAnswerStr = answertObject.getAsJsonObject("map").getAsJsonPrimitive("robotResponse")
					.getAsString();
			if (StringUtils.isEmpty(detailAnswerStr)) {
				logger.error("调用机器人接口异常。");
				answerMessage = CSMessageBuilder.createMessage(openId, MessageType.TEXT.getValue(),
						messageBuffer.append("机器人无法理解您的意思，如需人工，请回复序号9。").toString());
				answerTypeId = "1";
			} else {
				logger.info("智能机器人返回结果：{}。", detailAnswerStr);
				JsonObject detailAnswerObject = GsonUtil.json2JsonObject(detailAnswerStr);
				answerTypeId = detailAnswerObject.getAsJsonPrimitive("answerTypeId").getAsString();
				logger.info("智能机器人AnswerTypeId：{}。", answerTypeId);
				switch (answerTypeId) {
				case "1":
				case "2":
				case "3":
				case "7":
					// 统一提示转人工1、系统错误，2、敏感词，3、无法回答
					JsonObject singleNodeObject = detailAnswerObject.getAsJsonObject("singleNode");
					answerMessage = singleNodeObject.getAsJsonPrimitive("answerMsg").getAsString();
					messageBuffer.append(answerMessage).append("\n").append("如需人工，请回复序号：9。");
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), messageBuffer.toString());
					break;
				case "4":
					// 需要补问
					singleNodeObject = detailAnswerObject.getAsJsonObject("singleNode");
					answerMessage = singleNodeObject.getAsJsonPrimitive("answerMsg").getAsString();
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), answerMessage);
					break;
				case "5":
					// 多选问题
					JsonObject vagueNodeObject = detailAnswerObject.getAsJsonObject("vagueNode");
					JsonArray itemListJsonArray = vagueNodeObject.getAsJsonArray("itemList");
					String promptVagueMsg = vagueNodeObject.getAsJsonPrimitive("promptVagueMsg").getAsString();
					String endVagueMsg = vagueNodeObject.getAsJsonPrimitive("endVagueMsg").getAsString();
					StringBuffer messageBF = new StringBuffer();
					messageBF.append(promptVagueMsg).append("\n");
					for (int i = 0; i < itemListJsonArray.size(); i++) {
						JsonElement e = itemListJsonArray.get(i);
						JsonObject ee = e.getAsJsonObject();
						String num = ee.getAsJsonObject("num").getAsString();
						String question = ee.getAsJsonObject("question").getAsString();
						messageBF.append(num).append("、").append(question).append("\n");
					}
					messageBF.append(endVagueMsg);
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), messageBF.toString());
					break;
				case "6":
				case "8":
					singleNodeObject = detailAnswerObject.getAsJsonObject("singleNode");
					String isRichText = singleNodeObject.getAsJsonPrimitive("isRichText").getAsString();
					if ("0".equals(isRichText)) {
						answerMessage = singleNodeObject.getAsJsonPrimitive("answerMsg").getAsString();
						answerMessage = answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
								MessageType.TEXT.getValue(), answerMessage);
					} else {
						JsonArray newsList = singleNodeObject.getAsJsonArray("list");
						List<String> news = new ArrayList<>();
						for (int i = 0; i < newsList.size(); i++) {
							JsonElement e = newsList.get(i);
							JsonObject ee = e.getAsJsonObject();
							String title = ee.getAsJsonPrimitive("title").getAsString();
							String description = ee.getAsJsonPrimitive("description").getAsString();
							String picurl = ee.getAsJsonPrimitive("picurl").getAsString();
							String url = ee.getAsJsonPrimitive("url").getAsString();
							news.add(title);
							news.add(description);
							news.add(picurl);
							news.add(url);
						}
						answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
								MessageType.NEWS.getValue(), news.toArray(new String[] {}));
					}
					break;
				case "10":
					singleNodeObject = detailAnswerObject.getAsJsonObject("singleNode");
					answerMessage = singleNodeObject.getAsJsonPrimitive("answerMsg").getAsString();
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), answerMessage);
					logger.info("智能机器人遭访问攻击，如何处理？");
					break;
				case "11":
					singleNodeObject = detailAnswerObject.getAsJsonObject("singleNode");
					answerMessage = singleNodeObject.getAsJsonPrimitive("answerMsg").getAsString();
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), answerMessage);
					logger.info("智能机器人返回聊天过频，提示微信用户。");
					break;
				case "12":
					// 多选问题
					vagueNodeObject = detailAnswerObject.getAsJsonObject("vagueNode");
					itemListJsonArray = vagueNodeObject.getAsJsonArray("itemList");
					promptVagueMsg = vagueNodeObject.getAsJsonPrimitive("promptVagueMsg").getAsString();
					endVagueMsg = vagueNodeObject.getAsJsonPrimitive("endVagueMsg").getAsString();
					messageBF = new StringBuffer();
					messageBF.append(promptVagueMsg).append("\n");
					for (int i = 0; i < itemListJsonArray.size(); i++) {
						JsonElement e = itemListJsonArray.get(i);
						JsonObject ee = e.getAsJsonObject();
						String num = ee.getAsJsonObject("num").getAsString();
						String question = ee.getAsJsonObject("question").getAsString();
						messageBF.append(num).append("、").append(question).append("\n");
					}
					messageBF.append(endVagueMsg);
					answerMessage = CSMessageBuilder.createMessage(request.getFromUserName(),
							MessageType.TEXT.getValue(), messageBF.toString());
					break;
				default:
					break;
				}
				broker.response(answerMessage);
			}
			logger.info("发送结果至微信中继服务器，内容：{}。", answerMessage);
		}
		// cs.send(userBaseInfo.get("app_id"), answerMsg);
		userSessionInfo.put("conversationId", conversationId);
		userSessionInfo.put("answerTypeId", answerTypeId);
		try {
			logger.info("微信用户：{}，会话ID：{}，更新会话信息：{}。", request.getFromUserName(), CacheUtil.getSessionKey(sessionId),
					userSessionInfo);
			redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		long t2 = System.currentTimeMillis();
		logger.info("智能机器人服务微信用户：{}请求完成，耗时：{}毫秒。", request.getFromUserName(), (t2 - t1));
	}

	/**
	 * 创建全媒体格式的消息-发送人工坐席
	 * 
	 * @param userSessionInfo
	 * @param messageType
	 * @param msgContent
	 * @return
	 */
	private Map<String, String> createOmiisMessage(Map<String, String> userSessionInfo, String messageType,
			String msgContent) {
		Map<String, String> message = new HashMap<String, String>(userSessionInfo);
		// message.put("senderId", userSessionInfo.get("sender_id"));
		// message.put("senderName", userSessionInfo.get("sender_name"));
		// message.put("conversationId", userSessionInfo.get("conversationId"));
		message.put("msgType", messageType);
		message.put("msgContent", msgContent);
		return message;
	}

	/**
	 * 申请人工坐席
	 * 
	 * @param userSessionInfo
	 */
	private void sendResourceRequest(Map<String, String> userSessionInfo) {
		IRedisProcessor redis = SpringContextUtil.getBean(IRedisProcessor.class);
		String senderId = userSessionInfo.get("open_id");
		String sessionId = userSessionInfo.get("session_id");
		logger.info("微信用户：{}，申请人工坐席，SessionId：{}。", senderId, sessionId);
		Map<String, String> message = createOmiisMessage(userSessionInfo, ConversationType.RESOURCE_REQUEST.toString(),
				userSessionInfo.get("businessType"));
		// Map<String, String> message = new HashMap<String, String>();
		// message = new HashMap<String, String>();
		// message.put("senderId", userSessionInfo.get("sender_id"));
		// message.put("senderName", userSessionInfo.get("sender_name"));
		// message.put("conversationId", userSessionInfo.get("conversationId"));
		// message.put("msgType", ConversationType.RESOURCE_REQUEST.toString());
		// message.put("msgContent", userSessionInfo.get("businessType"));

		logger.info("发送申请坐席请求，内容：{}，会话信息：{}。", message, userSessionInfo);
		IOmiisMessager messager = SpringContextUtil.getBean(IOmiisMessager.class);
		messager.sendMessage(message);
		userSessionInfo.put("previous_message_time", DateUtil.getCurrentDate());
		userSessionInfo.put("previous_message_timestamp", DateUtil.getCurrentTimeMillis());
		userSessionInfo.put("conversation_type", ConversationType.RESOURCE_REQUEST.getValue());
		// SessionManager.getSesssionManager().updateSession(senderId,
		// userSessionInfo.get("previous_message_timestamp"));
		try {
			// 20161213 update by wangyq
			redis.hmset(CacheUtil.getSessionKey(sessionId), userSessionInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 微信客户入队
	 * 
	 * @param user_name
	 * @param open_id
	 * @return
	 */
	public synchronized Map<String, String> enqueue(String user_name, String open_id) {
		long t1 = System.currentTimeMillis();
		String queue_seq = "queue_seq";
		// String userid_seq = "userid_seq";
		// String queue_id = getContext().getDefaultQueue();
		logger.info("微信用户：{}开始入队。", open_id);
		IRedisProcessor processor = SpringContextUtil.getBean(IRedisProcessor.class);
		String session_id = "1000000";
		String user_id = null;
		{
			try {
				session_id = processor.incr(queue_seq);
				// user_id = processor.incr(userid_seq);
				// 从全媒体-Bus获取user_id
				String uri = "http://" + WeChatConfiguration.getIngleton().getValue("OMIIS_SERVER_HOST")
						+ ":7003/visitor/id/generate";
				user_id = executePost(uri, "", "");
				if (StringUtils.isEmpty(user_id)) {
					user_id = session_id;
					logger.error("从全媒体获取user_id失败，暂用session_id代替，session_id：{}。", session_id);
				}
				logger.info("从全媒体获取UserId：{}。", user_id);
			} catch (Exception e) {
				logger.error("从全媒体获取UserId失败：" + e.getMessage(), e);
			}
		}

		// TODO user_id 此处有问题，后续改正 20160809 by wangyq
		logger.info("微信用户：{}，会话ID：{},UserId：{}。", open_id, session_id, user_id);
		Map<String, String> userBaseInfo = new HashMap<String, String>();
		Map<String, String> userSessionInfo = new HashMap<String, String>();
		{
			IUserOperationApi userApi = SpringContextUtil.getBean(IUserOperationApi.class);
			String app_id = getContext().getAppIdByUserName(user_name);
			String jsonStr = (String) userApi.queryUserInfo(open_id, user_name);
			if (jsonStr.contains("errcode")) {
				logger.warn("从腾讯获取微信用户：{}，基本信息失败，错误信息：{}", open_id, GsonUtil.str2Map(jsonStr));
			} else {
				JsonObject jsonObject = GsonUtil.json2JsonObject(jsonStr);
				logger.info("json2JsonObject：{}", jsonObject);
				userBaseInfo.put("subscribe", jsonObject.get("subscribe").getAsString());
				userBaseInfo.put("openid", jsonObject.get("openid").getAsString());
				userBaseInfo.put("nickname", jsonObject.get("nickname").getAsString());
				userBaseInfo.put("sex", jsonObject.get("sex").getAsString());
				userBaseInfo.put("city", jsonObject.get("city").getAsString());
				userBaseInfo.put("country", jsonObject.get("country").getAsString());
				userBaseInfo.put("province", jsonObject.get("province").getAsString());
				userBaseInfo.put("headimgurl", jsonObject.get("headimgurl").getAsString());
				userBaseInfo.put("subscribe_time", jsonObject.get("subscribe_time").getAsString());
				userBaseInfo.put("app_id", app_id);
				// userBaseInfo.put("unionid",
				// jsonObject.get("unionid").getAsString());//关注多个公众号才返回
				userBaseInfo.put("remark", jsonObject.get("remark").getAsString());
				userBaseInfo.put("groupid", jsonObject.get("groupid").getAsString());
			}
			userBaseInfo.put("session_id", session_id);
			userBaseInfo.put("user_id", user_id);
			userBaseInfo.put("openid", open_id);
			logger.info("微信用户：{}，基本信息：{}", open_id, userBaseInfo);
			try {
				String result = processor.hmset(IPreferences.WECHAT_USER_PREFIX + open_id, userBaseInfo);
				// 将微信用户统一放入set集合中 2016-10-21 by wangyq
				processor.sadd(IPreferences.WECHAT_USER_SET, IPreferences.WECHAT_USER_PREFIX + open_id);
				processor.set(user_id, open_id);
				logger.info("更新微信用户：{}，基本信息：{}，操作结果：{}", open_id, userBaseInfo, result);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			userSessionInfo.put("session_id", session_id);
			userSessionInfo.put("sender_name",
					userBaseInfo.get("nickname") == null ? user_id : userBaseInfo.get("nickname"));
			// userSessionInfo.put("app_id", app_id);
			userSessionInfo.put("user_id", user_id);
			userSessionInfo.put("open_id", open_id);
			userSessionInfo.put("request_time", DateUtil.getCurrentDate());
			userSessionInfo.put("request_timestamp", DateUtil.getCurrentTimeMillis());
			userSessionInfo.put("status", "1");
			userSessionInfo.put("previous_message_time", userSessionInfo.get("request_time"));
			userSessionInfo.put("previous_message_timestamp", userSessionInfo.get("request_timestamp"));
			userSessionInfo.put("sender_id", open_id);
			userSessionInfo.put("conversation_type", ConversationType.ROBOT.getValue());
			// SessionManager.getSesssionManager().updateSession(open_id,
			// queueInfo.get("previous_message_timestamp"));
			try {
				String result = processor.hmset(IPreferences.WECHAT_SESSION_PREFIX + session_id, userSessionInfo);
				// 将微信用户sessionId存入set中
				processor.sadd(IPreferences.WECHAT_QUEUE_SET, IPreferences.WECHAT_SESSION_PREFIX + session_id);
				logger.info("更新微信用户：{}，会话ID：{}，排队信息：{}，操作结果：{}", open_id, session_id, userSessionInfo, result);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("微信用户：{}入队完成，会话ID：{}，由智能机器人提供服务，耗时：{}毫秒。", open_id, session_id, (t2 - t1));
		return userSessionInfo;
	}

}
